<!DOCTYPE html>
<html>
<head>
    <title>django-websocket</title>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript">//<![CDATA[
    $(function () {
        $('#connect_websocket').click(function () {
            if (window.s) {
                window.s.close()
            }
            /*创建socket连接*/
            var socket = new WebSocket("ws://" + window.location.host + "/echo/?id={{ id }}");
            socket.onopen = function () {
                console.log('WebSocket open');//成功连接上Websocket
            };
            socket.onmessage = function (e) {
                console.log('message: ' + e.data);//打印出服务端返回过来的数据
                if (e.data.length == 2){
                   console.log(e.data);
                }
                else{
                  $('#messagecontainer').prepend('<p>' + e.data + '</p>');
                }

            };
            // Call onopen directly if socket is already open
            if (socket.readyState == WebSocket.OPEN) socket.onopen();
            window.s = socket;
        });
        $('#send_message').click(function () {
            //如果未连接到websocket
            if (!window.s) {
                alert("websocket未连接.");
            } else {
                window.s.send($('#message').val());//通过websocket发送数据
            }
        });
        $('#close_websocket').click(function () {
            if (window.s) {
                window.s.close();//关闭websocket
                console.log('websocket已关闭');
            }
        });

    });
    //]]></script>
</head>
<body>
<br>
<input type="text" id="message" value="Hello, World!"/>
<button type="button" id="connect_websocket">查看间隔5s实时日志</button>
<button type="button" id="close_websocket">关闭实时日志</button>
<button type="button" id="close_websocket"><a href="/host/hostlist/"> 返回主机列表></a></button>
<h1>Received Messages</h1>
<div id="messagecontainer">

</div>
</body>
</html>
